using System;
using System.Web;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using Castle.ActiveRecord;

using Hadlow.Jobvertizer.Models;
using Hadlow.Jobvertizer.Repositories;

namespace Hadlow.Jobvertizer
{
	public class GlobalApplication : HttpApplication, IContainerAccessor
	{
		private static IWindsorContainer container;

		public GlobalApplication()
		{
		}

		#region IContainerAccessor

		public IWindsorContainer Container
		{
			get { return container; }
		}

		#endregion

		public void Application_OnStart()
		{
			container = new WindsorContainer(new XmlInterpreter());

            //ActiveRecordStarter.CreateSchema();
		}

		public void Application_OnEnd() 
		{
			container.Dispose();
		}

        protected void Application_OnAuthenticateRequest(Object sender, EventArgs e)
        {
            if (Context.User != null)
            {
                if (Context.User.Identity.IsAuthenticated)
                {
                    string name = Context.User.Identity.Name;

                    IUserRepository userRepository = container.Resolve<IUserRepository>();
                    User user = userRepository.GetUser(name);

                    System.Threading.Thread.CurrentPrincipal = Context.User = user;

                    return;
                }
            }

            System.Threading.Thread.CurrentPrincipal = 
                Context.User = 
                Hadlow.Jobvertizer.Models.User.Guest;
        }
	}
}
